<?php

class Main_IndexController extends Zend_Controller_Action
{
    protected $_model;
    protected $_authService;
    
    public function init()
    {
        $layout = $this->_helper->layout();
        $layout->setLayout('main');

        $this->_model = new Main_Model_AdminUser();

        $this->_authService = new Main_Service_Authentication();
        // add forms
        $this->view->loginForm = $this->getLoginForm();
        //@TODO:: add create user form
        $this->view->newuserForm = $this->getNewUserForm();
    }
    /**
     * function show the login form
     */
    public function indexAction()
    {
        // chaning the default layout for login page only
        $layout = $this->_helper->layout();
        $layout->setLayout('nolayout');
        // checking if user is already logged in
        if($this->_authService->getAuth()->hasIdentity())
                 $this->_redirect('/dashboard');
        
        if ($this->getRequest()->isPost())
        {
            $request = $this->getRequest();
            // Validate
            $form = $this->_forms['login'];
            if (!$form->isValid($request->getPost()))
            {
                return $this->render('index');
            }
            $this->_login();
        }
    }
    /*
     * performs the authentication & redirects user to dashboard
     */
    protected function _login()
    {
        $request = $this->getRequest();
        $form = $this->_forms['login'];
        $formValues = $form->getValues();
        if (false === $this->_authService->authenticate($formValues)) {
            $form->addError('Invalid');
            return $this->render('index');
        }
        
        $this->_redirect('/dashboard');

    }

    public function logoutAction()
    {
         $this->_authService->clear();
         $this->_redirect('/');
    }

    public function newAction()
    {
        $this->_helper->FlashMessenger('')->clearMessages();
        $this->_helper->FlashMessenger('')->setNamespace('header')->addMessage('New User');
        $this->_forward('edit');
    }

    /**
     * Used to show the user edit/create form
     */
    public function editAction()
    {
        $requst_params = $this->getRequest()->getParams();
       // if id is in request param && user is admin && is logged in       
        if( isset($requst_params['id']) && $requst_params['id'] !='' )
        {
            $this->_helper->FlashMessenger('')->clearMessages();
            $this->_helper->FlashMessenger('')->setNamespace('header')->addMessage('Edit User');
            $id  =  $requst_params['id'];
            $this->view->user = $this->_model->getUserById($id);

            $this->view->newuserForm = $this->getNewUserForm()->populate( $this->view->user->toArray() );
            
        }
    }

    public  function saveAction()
    {
        // echo '<pre>'; print_r($_REQUEST); echo '</pre>';
        $request = $this->getRequest();
        if (!$request->isPost()) {
            return $this->_helper->redirector('index');
        }
       
        if (false === $this->_model->saveUser($request->getPost())  )
        {
            $this->_helper->FlashMessenger('')->setNamespace('error')->addMessage('An error Occured');

            return $this->render('edit');
        }

        $this->_helper->FlashMessenger('')->setNamespace('success')->addMessage('User info saved');
        return $this->_redirect('/manage-users');
    }

    public function deleteAction()
    {
        if(!$this->_authService->getAuth()->hasIdentity())
            $this->_redirect('/');

         if (false === ($id = $this->_getParam('id',false))) {
            throw new WOW_Exception('Unknown user');
        }

        if($this->_model->deleteUser($id))
            $this->_helper->FlashMessenger('')->setNamespace('success')->addMessage('User Deleted');
        else
            $this->_helper->FlashMessenger('')->setNamespace('Error')->addMessage('An error occured');

        return $this->_redirect('/manage-users');
        
    }
    /*
     * Lists all the users for admin panel
     */
    public function listAction()
    {
        // checking if user is logged in 
        if(!$this->_authService->getAuth()->hasIdentity())
            $this->_redirect('/');

        $this->view->users = $this->_model->getAllUsers();
        
    }

    public function getLoginForm()
    {
        $urlHelper = $this->_helper->getHelper('url');

        $this->_forms['login'] = $this->_model->getForm('AdminuserLogin');
        $this->_forms['login']->setAction($urlHelper->url(array(
            'controller' => 'index',
            'action'     => 'index',
            ),
            'default'
        ));
        $this->_forms['login']->setMethod('post');

        return $this->_forms['login'];
    }

    public function getNewUserForm()
    {
        $urlHelper = $this->_helper->getHelper('url');

        $this->_forms['newuser'] = $this->_model->getForm('AdminuserNewuser');
        $this->_forms['newuser']->setAction($urlHelper->url(array(
            'controller' => 'index',
            'action'     => 'save',
            )
        ));
        $this->_forms['newuser']->setMethod('post');

        return $this->_forms['newuser'];
    }

}

